package com.canyou.utils;

import cn.afterturn.easypoi.word.WordExportUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

/**
 * word工具类
 *
 * @author cd
 */
@Slf4j
@Component
public class WordUtils {

    private static WordToPdf wordToPdf;

    private static final String DOCX = ".docx";

    private static final String PDF = ".pdf";

    @Autowired
    public void setWordToPdf(WordToPdf wordToPdf) {
        WordUtils.wordToPdf = wordToPdf;
    }

    /**
     * 导出word
     *
     * @param templatePath word模板地址
     * @param temDir       生成临时文件存放地址
     * @param fileName     文件名
     * @param params       替换的参数
     * @param response     HttpServletResponse
     */
    public static void exportWord(String templatePath, String temDir, String fileName, Map<String, Object> params, HttpServletResponse response) {
        File dir = new File(temDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        fileName = fileName + DOCX;
        try {
            XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-word");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("filename", URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("Access-Control-Expose-Headers", "filename");
            OutputStream out = response.getOutputStream();
            doc.write(out);
            out.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 导出Pdf
     *
     * @param templatePath word模板地址
     * @param temDir       生成临时文件存放地址
     * @param fileName     文件名
     * @param params       替换的参数
     * @param response     HttpServletResponse
     */
    public static void exportPdf(String templatePath, String temDir, String fileName, Map<String, Object> params, HttpServletResponse response) {
        File dir = new File(temDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 临时文件名，会删除
        String tempWordName = fileName + System.currentTimeMillis() + DOCX;
        String tempPdfName = fileName + System.currentTimeMillis() + PDF;
        // 导出的文件名
        String pdfFileName = fileName + PDF;
        String tmpWordPath = temDir + tempWordName;
        String tmpPdfPath = temDir + tempPdfName;
        File wordFile = new File(tmpWordPath);
        File pdfFile = new File(tmpPdfPath);
        try (FileOutputStream fos = new FileOutputStream(wordFile);) {
            XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
            doc.write(fos);
            if (wordToPdf.exeCommand(tmpWordPath, temDir)) {
                DownloadUtils.downFile(pdfFile, pdfFileName, "application/x-download", response);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            pdfFile.delete();
            wordFile.delete();
        }
    }

    /**
     * 删除目录下所有文件
     *
     * @param path
     * @return
     */
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                // 先删除文件夹里面的文件
                delAllFile(path + File.separator + tempList[i]);
                // 再删除空文件夹
                delFolder(path + File.separator + tempList[i]);
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 删除目录下所有文件夹
     *
     * @param folderPath
     * @return
     */
    public static void delFolder(String folderPath) {
        try {
            // 删除完里面所有内容
            delAllFile(folderPath);
            String filePath = folderPath;
            File myFilePath = new File(filePath);
            // 删除空文件夹
            myFilePath.delete();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}